package j.framework.base.service.impl;

import j.dao.support.MPTTA;
import j.data.tree.TreeData;
import j.data.tree.TreeNode;
import j.data.tree.TreeSetting;
import j.framework.base.service.SettingService;
import j.framework.core.LoginUser;
import j.framework.core.ServiceContext;
import j.framework.core.ServiceException;
import j.util.DES;
import j.util.StringUtils;
import j.util.jdbc.ResultSetHandler;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

/**
 * 系统设置
 * User: jason
 * Date: 2014/12/24 14:34
 */
public class SettingServiceImpl implements SettingService {
    /**
     * 根据参数说明获取参数信息
     * @param sc
     * @return
     */
    @Override
    public Map<String, Object> getSettingAsMap(ServiceContext sc) {
        return sc.getJdbcTemplate().queryForMap("select * from sys_setting where ss_key=?",sc.getDesId("key"));
    }

    /**
     * 保存参数
     * @param sc
     */
    @Override
    public String saveSetting(ServiceContext sc) {
        sc.getJdbcTemplate().executeByNamedSql("update sys_setting set name=:name,ss_value=:ss_value,dsc=:dsc,display_order=:display_order where ss_key=:ss_key",sc.params);
        return "<script>parent.doOk();</script>";
    }

    /**
     * 删除模块
     * @param sc
     */
    @Override
    public void deleteFunction(ServiceContext sc) {
        sc.getJdbcTemplate().execute("delete from sys_function where function_id=?",sc.getDesId("functionId"));
    }

    @Override
    public String buildQueryDictItemsWhere(LoginUser user, Map<String, String> queryParams, List<Object> args) {
        String dictId = DES.decrypt(queryParams.get("dictID"));
        if(StringUtils.isNullOrEmpty(dictId)){
            return "1!=1";
        }
        args.add(dictId);
        return "dict_id=?";
    }

    /**
     * 获取字典分类结构
     * @param sc
     * @return
     */
    @Override
    public TreeData getDictionaryCategoryTree(ServiceContext sc) {
        TreeSetting setting = new TreeSetting(false,false);
        setting.setNameFieldName("text");
        final TreeData td = new TreeData(setting);
        sc.getJdbcTemplate().queryForList("SELECT * FROM sys_dict_category", new ResultSetHandler() {
            @Override
            public void doResultSet(ResultSet rs) throws SQLException {
                TreeNode node = new TreeNode(rs.getString("dc_id"),rs.getString("name"));
                node.setpId(rs.getString("dc_pid"));
                td.addNode(node);
            }
        });
        return td;
    }

    /**
     * 获取字典树结构
     * @param sc
     * @return
     */
    @Override
    public TreeData getDictionaryTree(ServiceContext sc) {
        TreeSetting setting = new TreeSetting(false,false);
        setting.setNameFieldName("text");
        final TreeData td = new TreeData(setting);
        String sql = "SELECT * FROM (" +
                "SELECT dc_id AS id,dc_pid AS pid,name,0 AS is_sys FROM sys_dict_category " +
                "UNION" +
                " SELECT dict_id AS id,dc_id AS pid,name, is_sys FROM sys_dict " +
                ")AS t";
        sc.getJdbcTemplate().queryForList(sql, new ResultSetHandler() {
            @Override
            public void doResultSet(ResultSet rs) throws SQLException {
                TreeNode node = new TreeNode(DES.encrypt(rs.getString("id")),rs.getString("name"));
                node.setpId(DES.encrypt(rs.getString("pid")));
                td.addNode(node);
            }
        });
        return td;
    }

    @Override
    public void refreshTableWithLR(ServiceContext sc) {
        String tableName = sc.params.getString("table_name");
        String idColumnName = sc.params.getString("id_column_name");
        String pidColumnName = sc.params.getString("pid_column_name");
        String leftColumnName = sc.params.getString("left_column_name");
        String rightColumnName = sc.params.getString("right_column_name");
        String rootId = sc.params.getString("root_id");
        if(StringUtils.isNullOrEmpty(tableName)
                || StringUtils.isNullOrEmpty(idColumnName)
                || StringUtils.isNullOrEmpty(pidColumnName)
                || StringUtils.isNullOrEmpty(leftColumnName)
                || StringUtils.isNullOrEmpty(rightColumnName)
                || StringUtils.isNullOrEmpty(rootId)){
            throw new ServiceException("必须指定表名、ID字段名、父节点字段名、左值字段名、右值字段名及树表根级节点主键！");
        }
        MPTTA m = new MPTTA(sc.getJdbcTemplate().getDataSource(),
                tableName,idColumnName,pidColumnName,leftColumnName,rightColumnName,null,null);
        m.rebuildTree(rootId,1);
    }

    @Override
    public List<Map<String,Object>> getTableWithLRData(ServiceContext sc) {
        String tableName = sc.params.getString("table_name");
        String idColumnName = sc.params.getString("id_column_name");
        String nameColumnName = sc.params.getString("name_column_name");
        String pidColumnName = sc.params.getString("pid_column_name");
        String leftColumnName = sc.params.getString("left_column_name");
        String rightColumnName = sc.params.getString("right_column_name");
        if(StringUtils.isNullOrEmpty(tableName)
                || StringUtils.isNullOrEmpty(idColumnName)
                || StringUtils.isNullOrEmpty(pidColumnName)
                || StringUtils.isNullOrEmpty(nameColumnName)
                || StringUtils.isNullOrEmpty(leftColumnName)
                || StringUtils.isNullOrEmpty(rightColumnName)){
            throw new ServiceException("必须指定表名、ID字段名、父节点字段名、显示名称字段名、左值字段名及右值字段名！");
        }
        String sql = String.format("select %s as id,%s as name,%s as _parentId,%s as lft,%s as rgt from %s",
                idColumnName,nameColumnName,pidColumnName,leftColumnName,rightColumnName,tableName);
        List<Map<String,Object>> list = sc.getJdbcTemplate().queryForListMap(sql);
        for(Map<String,Object> map : list){
            if(null == map.get("_parentId")){
                map.put("_parentId","");
                break;
            }
        }
        return list;
    }
}
